﻿using Autofac;
using AutoRegistDependency.Attributes;
using AutoRegistDependency.Interface;
using HandyControl.Controls;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HandyWpf.Bus
{
    /// <summary>
    /// 用于handycontrol控件的dialog激活和关闭处理器，将vm和对应的page实例进行解耦，这样表单和list页面可以共用同一个vm
    /// </summary>
    [Component]
    public class HandyDialogEvent : IEventHandler<DialogEventData>
    {
        private readonly IComponentContext context;
        private readonly ConcurrentDictionary<string, Dialog> cache = new();
        public HandyDialogEvent(IComponentContext context)
        {
            this.context = context;
        }

        public void Handle(DialogEventData eventData)
        {
            var page = context.Resolve(eventData.TragetType);
            if (string.IsNullOrWhiteSpace(eventData.Token))
            {
                if (eventData.Open)
                {
                    
                    var diaog = Dialog.Show(page);
                    _ = cache.Remove(eventData.TragetType.Name, out var _);
                    cache.TryAdd(eventData.TragetType.Name, diaog);
                }
                else
                {
                    if(cache.TryGetValue(eventData.TragetType.Name,out var dialog))
                    {
                        dialog.Close();
                        _ = cache.Remove(eventData.TragetType.Name, out var r);
                        r = null;
                    }
                }
            }
            else
            {
                if (eventData.Open)
                {
                    Dialog.Show(page,eventData.Token);
                }
                else
                {
                    Dialog.Close(eventData.Token);
                }
            }


        }
    }
    public class DialogEventData()
    {
        public bool Open { get; set; } = true;
        public Type TragetType { get; set; }
        public string Token { get; set; }
    }
}
